package cn.com.hhrcw.validator.resume.util;

import cn.com.hhrcw.entity.*;
import cn.com.hhrcw.service.*;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 简历输入验证
 *
 * @author leeson
 */
@Slf4j
@Component
public class ResumeRequiredValidationUtil {
    public static final String SEPARATOR = "、";

    @Autowired
    private ICvResumeService cvResumeService;

    @Autowired
    private ICvUserEduInfoService cvUserEduInfoService;

    @Autowired
    private ICvUserWorkInfoService cvUserWorkInfoService;

    @Autowired
    private ICvFamilyMemberService cvFamilyMemberService;

    @Autowired
    private ICvWorkIntentionService cvWorkIntentionService;

    @Autowired
    private ICvLanguageLevelService cvLanguageLevelService;

    @Autowired
    private ResumePiInfoRequiredValidationUtil resumePiInfoRequiredValidationUtil;

    /**
     * 发现错误是否立即中断
     *
     * @param resumeId
     * @param isInterrupt true 中断 fasle 不中断
     * @return
     */
    public Result isValid(String resumeId, boolean isInterrupt) {
        log.info("开始验证 v1.0.6");

        StringBuilder sb = new StringBuilder();


        CvResume resume = cvResumeService.getById(resumeId);

        List<CvUserWorkInfo> userWorkInfos = cvUserWorkInfoService.lambdaQuery()
            .eq(CvUserWorkInfo::getResumeId, resume.getId())
            .eq(CvUserWorkInfo::getDelFlag, 0)
            .list();
        List<CvFamilyMember> familyMembers = cvFamilyMemberService.lambdaQuery()
            .eq(CvFamilyMember::getResumeId, resume.getId())
            .eq(CvFamilyMember::getDelFlag, 0)
            .list();

        Result piInfoRet = resumePiInfoRequiredValidationUtil.isValid(resume);
        if (!piInfoRet.isSuccess()) {
            if (isInterrupt) {
                return Result.error(piInfoRet.getMessage());
            } else {
                sb.append(piInfoRet.getMessage()).append(SEPARATOR);
            }
        }
        boolean isSchool = resume.getResumeType() == 2;
        if (isSchool) {
            log.info("校招简历验证");

            if (StringUtils.isBlank(resume.getMajorResearchDirection())) {
                String msg = "请完善主要研究方向及成果";
                sb.append(msg).append(SEPARATOR);

            }
            if (StringUtils.isBlank(resume.getSelfEvaluation())) {
                String msg = "请完善自我综合评价";
                sb.append(msg).append(SEPARATOR);

            }
            if (StringUtils.isBlank(resume.getOtherSituations())) {
                String msg = "请完善其他情况（校内任职情况等）";
                sb.append(msg).append(SEPARATOR);

            }
        }

        if (resume.getResumeType() == 1) {

            List<CvWorkIntention> workIntentions = cvWorkIntentionService.lambdaQuery()
                .eq(CvWorkIntention::getResumeId, resume.getId())
                .eq(CvWorkIntention::getDelFlag, false)
                .list();
            //期望职位
            if (CollUtil.isEmpty(workIntentions)) {

                String msg = "请完善期望职位";
                sb.append(msg).append(SEPARATOR);
                //立即中断返回
                if (isInterrupt) {
                    return Result.error(msg);
                }
            }

        }

        //工作/实习 经历
        if (CollUtil.isEmpty(userWorkInfos)) {

            String msg = "请完善工作(实习)经历";
            sb.append(msg).append(SEPARATOR);
            //立即中断返回
            if (isInterrupt) {
                return Result.error(msg);
            }

        } else {
            //公用需要验证的工作经历
            for (CvUserWorkInfo info : userWorkInfos) {
                boolean match = Stream.of(
                    //请填写公司名称
                    info.getCompanyName(),
                    info.getR2(),
                    info.getR1(),
                    // 请选择所任职位
                    info.getPositionName(),
                    //在职时间
                    info.getWorkStartTime(), info.getWorkEndTime(),
                    //请填写工作内容'
                    info.getWorkContent()
                ).anyMatch(e -> {
                    if (e instanceof String && StrUtil.isBlank(Convert.toStr(e))) {
                        return true;
                    }
                    return e == null;
                });
                if (match) {
                    String msg = "请完善工作/实习经历";
                    sb.append(msg).append(SEPARATOR);
                    //立即中断返回
                    if (isInterrupt) {
                        return Result.error(msg);
                    }

                }
            }

            if (resume.getResumeType() == 1 && StringUtils.isBlank(resume.getMajorWorkPerformance())) {
                String msg = "请完善主要工作业绩";
                sb.append(msg).append(SEPARATOR);
                //立即中断返回
                if (isInterrupt) {
                    return Result.error(msg);
                }
            }
            if (resume.getResumeType() == 1) {
                //社招招简历
                for (CvUserWorkInfo info : userWorkInfos) {
                    boolean match = Stream.of(
                        //请填写单位规模
                        info.getR3(),
                        //请填写下属人数
                        info.getR5(),
                        //请填写上级职位
                        info.getR4(),
                        //请填写离职原因
                        info.getR6()
                    ).anyMatch(e -> {
                        if (e instanceof String && StrUtil.isBlank(Convert.toStr(e))) {
                            return true;
                        }
                        return e == null;
                    });
                    if (match) {
                        String msg = "请完善工作/实习经历";
                        sb.append(msg).append(SEPARATOR);
                        //立即中断返回
                        if (isInterrupt) {
                            return Result.error(msg);
                        }

                    }
                }//end  of for

                List<CvLanguageLevel> languageLevels = cvLanguageLevelService.lambdaQuery()
                    .eq(CvLanguageLevel::getResumeId, resume.getId())
                    .eq(CvLanguageLevel::getDelFlag, 0)
                    .list();

                if (CollUtil.isEmpty(languageLevels)) {
                    String msg = "请完善语言能力";
                    sb.append(msg).append(SEPARATOR);
                    //立即中断返回
                    if (isInterrupt) {
                        return Result.error(msg);
                    }
                }
            } else if (isSchool) {
                //校招简历
            }

        }
        //学历
        List<CvUserEduInfo> eduInfoList = cvUserEduInfoService.lambdaQuery()
            .eq(CvUserEduInfo::getResumeId, resume.getId())
            .eq(CvUserEduInfo::getDelFlag, 0)
            .list();
        if (CollUtil.isEmpty(eduInfoList)) {
            //
            String msg = "教育经历需从高中/中专填写：高中/中专(必填)、本科/大专(必填)、研究生（如有）";
            sb.append(msg).append(SEPARATOR);
            //立即中断返回
            if (isInterrupt) {
                return Result.error(msg);
            }
        } else {
            Integer[] eduLevelArray = eduInfoList.stream().map(CvUserEduInfo::getEduLevel).collect(Collectors.toList()).toArray((new Integer[eduInfoList.size()]));
            String eduLevel = ArrayUtil.join(eduLevelArray, ",");
            log.info("学历={}", eduLevel);
            boolean contains = !eduLevel.contains("1") && !eduLevel.contains("2");
            if (contains) {
                String msg = "教育经历需从高中/中专填写：高中/中专(必填)、本科/大专(必填)、研究生（如有）";
                sb.append(msg).append(SEPARATOR);
                //立即中断返回
                if (isInterrupt) {
                    return Result.error(msg);
                }
            }
            // 2023-03-03 去除教育经历对大专/本科的校验
//            contains = !eduLevel.contains("3") && !eduLevel.contains("4");
//            if (contains) {
//                String msg = "教育经历需从高中/中专填写：高中/中专(必填)、本科/大专(必填)、研究生（如有）";
//                sb.append(msg).append(SEPARATOR);
//                //立即中断返回
//                if (isInterrupt) {
//                    return Result.error(msg);
//                }
//            }

            //学历判断
//            for (CvUserEduInfo info : eduInfoList) {
//                boolean match = Stream.of(
//                        info.getStartEduTime(),
//                        info.getEndEduTime(),
//                        info.getSchoolName(),
//                        info.getEduLevel(),
//                        // 学位 1 学士 2 硕士 3 博士
//                        info.getR1(),
//                        // 是否全日制 1 是 2 不是
//                        info.getR2()
//                    )
//                    .anyMatch(e -> {
//                        if (e instanceof String && StrUtil.isBlank(Convert.toStr(e))) {
//                            return true;
//                        }
//                        return e == null;
//                    });
//                if (match) {
//                    String msg = "请完善学历信息";
//                    sb.append(msg).append(SEPARATOR);
//                    //立即中断返回
//                    if (isInterrupt) {
//                        return Result.error(msg);
//                    }
//                }
//            }
        }

        //家庭成员
        if (CollUtil.isEmpty(familyMembers)) {
            String msg = "请完善家庭成员信息";
            sb.append(msg).append(SEPARATOR);
            //立即中断返回
            if (isInterrupt) {
                return Result.error(msg);
            }
        } else {
            //历史数据必填项验证
            for (CvFamilyMember familyMember : familyMembers) {

                boolean match = Stream.of(
                        familyMember.getAppellation(),
                        familyMember.getName(),
                        familyMember.getBirthday(),
                        familyMember.getPolitics(),
                        familyMember.getCompany(),
                        familyMember.getPosition(),
                        familyMember.getPhone()
                    )
                    .anyMatch(e -> {
                        if (e instanceof String && StrUtil.isBlank(Convert.toStr(e))) {
                            return true;
                        }
                        return e == null;
                    });
                if (match) {
                    String msg = "请完善家庭成员信息";
                    sb.append(msg).append(SEPARATOR);
                    //立即中断返回
                    if (isInterrupt) {
                        return Result.error(msg);
                    }
                }
            }
        }

        if (StringUtils.isBlank(sb.toString())) {
            return Result.ok();
        } else {
            return Result.error(sb.toString());

        }

    }
}
